//
//  SSMap.swift
//  SSBaseTool
//
//  Created by 松松 on 2019/6/10.
//

import Foundation

public protocol SSMap {
    init(fromDictionary dictionary: [String:Any])
    func toDictionary() -> [String:Any]
}

public func ssMapArr<T:SSMap>(type:T.Type,_ arr:Any) ->[T]?{

    var modelArr : [[String:Any]]? =  arr as? [[String:Any]]

    if let str = arr as? String{
        let data = str.data(using: .utf8)!
        if let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments){
            if let jsonDic = json as? [[String:Any]]{
                modelArr = jsonDic
            }
        }
    }

    if modelArr != nil{
        var resultArr = [T]()
        for item in modelArr!{
            let ententy = T(fromDictionary: item)
            resultArr.append(ententy)
        }
        return resultArr
    }
    return nil
}

public func ssMap<T:SSMap>(type:T.Type,_ object:Any) -> T?{
    var mapDic : [String:Any]? =  object as? [String:Any]

    if let str = object as? String{
        let data = str.data(using: .utf8)!
        if let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments){
            if let jsonDic = json as? [String:Any]{
                mapDic = jsonDic
            }
        }
    }
    if mapDic != nil{
        let resultModel = T(fromDictionary: mapDic!)
        return resultModel
    }
    return nil
}

